package com.ruoyi.system.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.util.concurrent.*;


/**
 * @Description: 任务执行
 * @author: wangp
 * @date: 2025年03月11日 16:15
 */
@Component("taskScheduler")
public class TaskScheduler {
    private final DelayQueue<DelayedTask> queue = new DelayQueue<>();
    private final ExecutorService executor;

    public TaskScheduler(@Value("${task.scheduler.core-pool-size:2}") int corePoolSize,
                         @Value("${task.scheduler.maximum-pool-size:2}") int maximumPoolSize,
                         @Value("${task.scheduler.keep-alive-time:0}") long keepAliveTime) {
        this.executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize,
                keepAliveTime, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>(), new ThreadPoolExecutor.AbortPolicy());
        startConsumer();
    }

    // 启动消费者线程
    private void startConsumer() {
        Thread consumerThread = new Thread(() -> {
            while (!Thread.currentThread().isInterrupted()) {
                try {
                    DelayedTask task = queue.take();  // 阻塞直到有任务到期
                    executor.execute(task::execute);  // 提交到线程池执行
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        });
        consumerThread.setDaemon(true);  // 设置为守护线程（可选）
        consumerThread.start();
    }

    // 动态添加任务
    public void submit(Runnable task, long delay, TimeUnit unit) {
        queue.add(new DelayedTask(task, delay, unit));
    }

    // 关闭调度器
    @PreDestroy
    public void shutdown() {
        executor.shutdown();
    }
}